package com.example.imserver.controller;

import com.example.imserver.entity.User;
import com.example.imserver.service.UserService;
import com.example.imserver.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;
    
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        return userService.login(username, password);
    }
    
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String username = request.get("username");
            String password = request.get("password");
            String nickname = request.get("nickname");
            
            User user = userService.register(username, password, nickname);
            String token = JwtUtil.generateToken(user.getId());
            
            result.put("success", true);
            result.put("token", token);
            result.put("user", user);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @GetMapping("/me")
    public Map<String, Object> getCurrentUser(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            Long userId = JwtUtil.getUserIdFromToken(token);
            if (userId != null) {
                Optional<User> user = userService.getUserById(userId);
                if (user.isPresent()) {
                    result.put("success", true);
                    result.put("user", user.get());
                } else {
                    result.put("success", false);
                    result.put("message", "用户不存在");
                }
            } else {
                result.put("success", false);
                result.put("message", "无效的token");
            }
        } else {
            result.put("success", false);
            result.put("message", "未登录");
        }
        return result;
    }
    
    @PutMapping("/me")
    public Map<String, Object> updateCurrentUser(@RequestBody Map<String, String> requestBody, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            Long userId = JwtUtil.getUserIdFromToken(token);
            if (userId != null) {
                Optional<User> userOpt = userService.getUserById(userId);
                if (userOpt.isPresent()) {
                    User user = userOpt.get();
                    if (requestBody.containsKey("nickname")) {
                        user.setNickname(requestBody.get("nickname"));
                    }
                    if (requestBody.containsKey("avatar")) {
                        user.setAvatar(requestBody.get("avatar"));
                    }
                    User updatedUser = userService.updateUser(user);
                    result.put("success", true);
                    result.put("user", updatedUser);
                } else {
                    result.put("success", false);
                    result.put("message", "用户不存在");
                }
            } else {
                result.put("success", false);
                result.put("message", "无效的token");
            }
        } else {
            result.put("success", false);
            result.put("message", "未登录");
        }
        return result;
    }
}

